package com.raymond.http.netty;

import com.raymond.http.config.HttpConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.pool.*;
import io.netty.util.internal.PlatformDependent;
import io.netty.util.internal.ReadOnlyIterator;
import lombok.extern.slf4j.Slf4j;

import java.io.Closeable;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import static io.netty.util.internal.ObjectUtil.checkNotNull;

/**
 * 默认连接池
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-12-11 17:54
 */
@Slf4j
public class DefaultChannelPoolMap implements  Iterable<Map.Entry<HttpAddress, HttpFixedChannelPool>>, Closeable {

    private final ConcurrentMap<HttpAddress, HttpFixedChannelPool> map = PlatformDependent.newConcurrentHashMap();

    private Bootstrap bootstrap;

    private HttpConfig config;

    private HandlerInstance instance;

    public DefaultChannelPoolMap(Bootstrap bootstrap, HttpConfig config, HandlerInstance instance) {
        this.bootstrap = bootstrap;
        this.config = config;
        this.instance = instance;
    }



    public final HttpFixedChannelPool get(HttpAddress key) {
        HttpFixedChannelPool pool = map.get(checkNotNull(key, "key"));
        if (pool == null) {
            pool = newPool(key);
            HttpFixedChannelPool old = map.putIfAbsent(key, pool);
            if (old != null) {
                // We need to destroy the newly created pool as we not use it.
                pool.close();
                pool = old;
            }
        }
        return pool;
    }
    /**
     * Remove the {@link ChannelPool} from this {@link AbstractChannelPoolMap}. Returns {@code true} if removed,
     * {@code false} otherwise.
     *
     * Please note that {@code null} keys are not allowed.
     */
    public final boolean remove(HttpAddress key) {
        HttpFixedChannelPool pool =  map.remove(checkNotNull(key, "key"));
        if (pool != null) {
            pool.close();
            return true;
        }
        return false;
    }

    @Override
    public final Iterator<Map.Entry<HttpAddress, HttpFixedChannelPool>> iterator() {
        return new ReadOnlyIterator<Map.Entry<HttpAddress, HttpFixedChannelPool>>(map.entrySet().iterator());
    }

    /**
     * Returns the number of {@link ChannelPool}s currently in this {@link AbstractChannelPoolMap}.
     */
    public final int size() {
        return map.size();
    }

    /**
     * Returns {@code true} if the {@link AbstractChannelPoolMap} is empty, otherwise {@code false}.
     */
    public final boolean isEmpty() {
        return map.isEmpty();
    }


    public final boolean contains(HttpAddress key) {
        return map.containsKey(checkNotNull(key, "key"));
    }

    /**
     * Called once a new {@link ChannelPool} needs to be created as non exists yet for the {@code key}.
     */
    protected HttpFixedChannelPool newPool(HttpAddress address) {
        String ip = address.getHost();
        int port = address.getPort();
        log.debug("ip:{},port:{}", ip, port);
        return new HttpFixedChannelPool(bootstrap.remoteAddress(ip, port),
                new DefaultChannelPoolHandler(config, instance, address.isSsl()),
                config.getMaxConnections(),
                config.isLastRecentUsed());
    }

    @Override
    public final void close() {
        for (HttpAddress key: map.keySet()) {
            remove(key);
        }
    }


}
